package HibernateOrederManagement.app;

import java.util.Date;
import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.query.Query;

import HibernateOrderManagerment.bean.OrderStatus;
import HibernateOrderManagerment.bean.Orders;
import HibernateOrderManagerment.bean.User;

public class OrdersDao {
private Session session;
	
	public OrdersDao(Session session){
		this.session=session;
	}
	
	public List<Orders> list(){
		Query<Orders> query=session.createQuery("from Orders",Orders.class);
		
		return query.getResultList();
	}
	public Orders getOrdersById(long id){
		return session.get(Orders.class,id);
	}
	
	public Orders getByDateTime(Date time){
		Query<Orders> query =session.createQuery("from Orders where dateTime=:time",Orders.class);
		query.setParameter("time", time);
		return query.getSingleResult();
	}
	public Orders getByCustomerId(long id){
		UserDao dao =new UserDao(session);
		User customer = dao.getUserById(id);
		Query<Orders> query =session.createQuery("from Orders where customer=:customer",Orders.class);
		query.setParameter("customer", customer);
		return query.getSingleResult();
	}
	public Orders getByOrderStatusId(long  id){
		OrderStatusDao dao =new OrderStatusDao(session);
		OrderStatus orderStatus =dao.getOrderStatusById(id);
		Query<Orders> query =session.createQuery("from Orders where OrderStatus=:orderStatus",Orders.class);
		query.setParameter("orderStatus", orderStatus);
		return query.getSingleResult();
	}

	
	
	public void insert(Orders orders) {
		Transaction tx = session.beginTransaction();
		try {

			session.save(orders);
			tx.commit();
		} catch (HibernateException e) {
			e.printStackTrace();
			tx.rollback();
		}
	}
	public void update(Orders orders){
		Transaction tx = session.beginTransaction();
		try {

			session.update(orders);
			tx.commit();
		} catch (HibernateException e) {
			e.printStackTrace();
			tx.rollback();
		}
		
	}
	public void delete(Orders orders){
		Transaction tx = session.beginTransaction();
		try {
			
			session.delete(orders);
			tx.commit();
		} catch (HibernateException e) {
			e.printStackTrace();
			tx.rollback();
		}
		
	}


}
